package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.req.SetmealDto;
import com.itheima.reggie.mapper.SetMealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;


    @Override
    @Transactional
    public void saveSetmeal(SetmealDto setmealDto) {
        //保存菜品信息
        this.save(setmealDto);
        //获取套餐中的菜品信息
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        //遍历集合，将套餐中的id赋值给套餐菜品
        dishes = dishes.stream().map(dish -> {
            dish.setSetmealId(setmealDto.getId());
            return dish;
        }).collect(Collectors.toList());
        //将套餐中的菜品信息保存
        setmealDishService.saveBatch(dishes);

    }

    @Override
    @Transactional
    public void updateSetmeal(SetmealDto setmealDto) {
        //将setmeal更新
        this.updateById(setmealDto);
        //获取到当前需要修改套餐的id
        Long id = setmealDto.getId();
        //根据id删除套餐中的菜品信息
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        setmealDishService.remove(wrapper);
        //获取到套餐中的菜品信息
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        //将提交的菜品保存到表中
        for (SetmealDish dish : dishes) {
            dish.setSetmealId(id);
        }
        setmealDishService.saveBatch(dishes);
    }


}
